#!/usr/bin/env bash
set -e

add=0
for f in packages/*; do
	if [[ -z $CHART || $CHART == $(basename -- ${f}) ]]; then
		mkdir -p assets/$(basename -- ${f})
		if [[ -d ${f}/overlay ]]; then
			cp -R ${f}/overlay/* ${f}/charts
		fi
		if [[ -f ${f}/package.yaml ]]; then
			version=$(yq r ${f}/charts/Chart.yaml version)
			packageVersion=$(yq r ${f}/package.yaml packageVersion)
			yq w -i ${f}/charts/Chart.yaml 'version' "${version}${packageVersion}"
		fi
		helm package ${f}/charts --destination assets/$(basename -- ${f})
		git checkout assets/$(basename -- ${f})/"$(basename -- ${f})-$(yq r ${f}/charts/Chart.yaml version).tgz" 2>/dev/null || true
	fi
done

if [[ -n $(git ls-files --other | grep "tgz") ]]; then
	helm repo index --merge ./assets/index.yaml --url assets assets
	cp ./assets/index.yaml .
fi
